﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using App.Utilities.Web.Handlers;
using System.Data;
using CRMBiz;
using Newtonsoft.Json;
using CRMEntity;
using CRMBiz.CalculateInterest;
using CRMBiz.AM;
using CRMWeb.Utilities.Context;

namespace CRMWeb.WebServices.AM
{
    /// <summary>
    /// Summary description for ApplicationContract
    /// </summary>
    public class ApplicationContract : BaseHandler
    {
        public override void OnMethodInvoke(OnMethodInvokeArgs e)
        {
            context.Response.Cache.SetCacheability(HttpCacheability.ServerAndNoCache);
            context.Response.Cache.SetExpires(DateTime.MinValue);
            context.Response.Cache.SetNoStore();
            SetResponseContentType(ResponseContentTypes.HTML);
        }

        public override void AfterMethodInvoke(object result)
        {
            base.AfterMethodInvoke(result);
        }

        public void calculateByTerm(double loanAmount, double establishFee, double monthlyFee, string settleDate, string paymentDate, int repaymentBy, int term)
        {
            try
            {
                DateTime settlementDate = Convert.ToDateTime(settleDate);
                DateTime firstPaymentDate = Convert.ToDateTime(paymentDate);
                double totEstablishmentFee = SACC.GetTotalEstablishmentFee(loanAmount, establishFee);
                double totMonthlyFee = SACC.GetTotalMonthlyFee(loanAmount, term, repaymentBy, monthlyFee, settlementDate, firstPaymentDate);
                double totFee = totEstablishmentFee + totMonthlyFee;

                DataTable dtSchedule = new DataTable();
                dtSchedule = SACC.SACCCalculateByTerm(loanAmount, term, repaymentBy, totEstablishmentFee, totMonthlyFee, settlementDate, firstPaymentDate);
                string repaymentAmt = dtSchedule.Rows[0]["Repayment"].ToString();
                DateTime lastPaymentDate = SACC.GetLastPaymentDate(settlementDate, firstPaymentDate, repaymentBy, term);
                context.Response.Write(repaymentAmt + '#' + totEstablishmentFee.ToString() + '#' + totMonthlyFee.ToString() + '#' + totFee + '#' + lastPaymentDate.ToString("dd/MM/yyyy"));
            }
            catch (Exception ex)
            {
                ErrorHandler.saveErrorLog(ex,CMSContext.CurrentUser.MemberName);
            }
        }

        public void GetPaymentTermsByMonth(string settleDate, string paymentDate, int term, int repaymentBy)
        {
            try
            {
                DateTime settlementDate = Convert.ToDateTime(settleDate);
                DateTime firstPaymentDate = Convert.ToDateTime(paymentDate);
                string paymentTermsByMonth = SACC.GetPaymentTermsByMonth(term, repaymentBy, settlementDate, firstPaymentDate).ToString();
                context.Response.Write(paymentTermsByMonth);
            }
            catch (Exception ex)
            {
                ErrorHandler.saveErrorLog(ex,CMSContext.CurrentUser.MemberName);
            }
        }


        public void PrepareSchedule(double loanAmount, double establishFee, double monthlyFee, string settleDate, string paymentDate, int repaymentBy, int term)
        {
            string strJson = string.Empty;
            try
            {
                DateTime settlementDate = Convert.ToDateTime(settleDate);
                DateTime firstPaymentDate = Convert.ToDateTime(paymentDate);

                double totEstablishmentFee = SACC.GetTotalEstablishmentFee(loanAmount, establishFee);
                double totMonthlyFee = SACC.GetTotalMonthlyFee(loanAmount, term, repaymentBy, monthlyFee, settlementDate, firstPaymentDate);
                double totFee = totEstablishmentFee + totMonthlyFee;

                DataTable dtSchedule = new DataTable();
                dtSchedule = SACC.SACCCalculateByTerm(loanAmount, term, repaymentBy, totEstablishmentFee, totMonthlyFee, settlementDate, firstPaymentDate);
                strJson = JsonConvert.SerializeObject(dtSchedule);
                context.Response.Write(strJson);
            }
            catch (Exception ex)
            {
                ErrorHandler.saveErrorLog(ex,CMSContext.CurrentUser.MemberName);
            }
        }

        public void getDataForApplicationContract(int appid)
        {
            DataSet ds;
            try
            {
                ds = LoanContractHandler.SelectDataForLoanContract(appid);
                context.Response.Write(JsonConvert.SerializeObject(ds.Tables[0]));
            }
            catch (Exception ex)
            {
                ErrorHandler.saveErrorLog(ex,CMSContext.CurrentUser.MemberName);
            }
        }

        public void selectLoanContract(int LoanContractID)
        {
            DataSet ds;
            try
            {
                ds = LoanContractHandler.SelectLoanContract(LoanContractID);
                context.Response.Write(JsonConvert.SerializeObject(ds.Tables[0]));
            }
            catch (Exception ex)
            {
                ErrorHandler.saveErrorLog(ex,CMSContext.CurrentUser.MemberName);
            }
        }
        public void saveContractDraft(int app_id, int ContactID, double LoanAmount, double EstablishFee, double MonthlyFee, string SettleDate, string firstPaymentDate, string LastPaymentDate, int RepaymentBy, int Term, int TermbyMonth, string BankName, string BSB,
            string AccName, string AccNo, string FirstName, string MiddleName, string LastName, string DateBirth, string DriverLicense, string StreetNo, string Street, string Suburb, string State, string PostCode, int updateClientProfile, string historyOperator, string filePath)
        {
            bool result = false;
            try
            {
                result = LoanContractHandler.saveContractDraft(app_id, ContactID, LoanAmount, EstablishFee, MonthlyFee, SettleDate, firstPaymentDate, LastPaymentDate, RepaymentBy, Term, TermbyMonth, BankName, BSB, AccName, AccNo, FirstName, MiddleName, LastName,
                     DateBirth, DriverLicense, StreetNo, Street, Suburb, State, PostCode, updateClientProfile, historyOperator, filePath);
                context.Response.Write(result);
            }
            catch (Exception ex)
            {
                ErrorHandler.saveErrorLog(ex,CMSContext.CurrentUser.MemberName);
            }
        }
        public void generateContract(int app_id, int ContactID, double LoanAmount, double EstablishFee, double MonthlyFee, string SettleDate, string firstPaymentDate, string LastPaymentDate, int RepaymentBy, int Term, int TermbyMonth, decimal repaymentAmt, decimal totalEstFee, decimal totalmonthFee, string BankName, string BSB,
            string AccName, string AccNo, string FirstName, string MiddleName, string LastName, string DateBirth, string DriverLicense, string StreetNo, string Street, string Suburb, string State, string PostCode, string historyOperator, int updateClientProfile, string filePath)
        {
            string resposnse = string.Empty;
            try
            {
                resposnse = LoanContractHandler.generateContract(app_id, ContactID, LoanAmount, EstablishFee, MonthlyFee, SettleDate, firstPaymentDate, LastPaymentDate, RepaymentBy, Term, TermbyMonth, repaymentAmt, totalEstFee, totalmonthFee,
                    BankName, BSB, AccName, AccNo, FirstName, MiddleName, LastName, DateBirth, DriverLicense, StreetNo, Street, Suburb, State, PostCode, historyOperator, updateClientProfile, filePath);
                context.Response.Write(resposnse);
            }
            catch (Exception ex)
            {
                ErrorHandler.saveErrorLog(ex,CMSContext.CurrentUser.MemberName);
            }
        }

        public void createLoan(int app_id, int ContactID, double LoanAmount, double EstablishFee, double MonthlyFee, string SettleDate, string firstPaymentDate, int RepaymentBy, int Term, string BankName, string BSB, string FirstName, string MiddleName, string LastName, string historyOperator, string filePath)
        {
            try
            {
                // LoanContractHandler.generateContract(app_id, ContactID, LoanAmount, EstablishFee, MonthlyFee, SettleDate, firstPaymentDate, RepaymentBy, Term, BankName, BSB, FirstName, MiddleName, LastName, historyOperator, filePath);
            }
            catch (Exception ex)
            {
                ErrorHandler.saveErrorLog(ex,CMSContext.CurrentUser.MemberName);
            }
        }
        public void fillContractHistory(int appid)
        {
            DataSet ds;
            try
            {
                ds = LoanContractHandler.FillContractHistory(appid);
                context.Response.Write(JsonConvert.SerializeObject(ds.Tables[0]));
            }
            catch (Exception ex)
            {
                ErrorHandler.saveErrorLog(ex,CMSContext.CurrentUser.MemberName);
            }
        }

        public void getDataForApplicationContractTemplate(int app_id, int LoanContractID, double loanAmount, double establishFee, double monthlyFee, string settleDate, string paymentDate, int repaymentBy, int term)
        {
            string returnFileName;
            try
            {
                returnFileName = LoanContractHandler.getDataForApplicationContractTemplate(app_id, LoanContractID, loanAmount, establishFee, monthlyFee, settleDate, paymentDate, repaymentBy, term);
                context.Response.Write(JsonConvert.SerializeObject(returnFileName));
            }
            catch (Exception ex)
            {
                ErrorHandler.saveErrorLog(ex,CMSContext.CurrentUser.MemberName);
            }

        }

    }
}